import { getPreviewDetail } from "@Api/productApi"
import { Button, Modal, Popover, Space, Tag } from "@bytedance/mona-ui"
// import priceCommodity from "@Styles/priceCommodity.scss?inline"
import type {
  PlasmoCSConfig,
  PlasmoCSUIProps,
  PlasmoGetInlineAnchorList,
  PlasmoGetStyle
} from "plasmo"
import type { FC } from "react"
import React, { useEffect, useState } from "react"
import { Provider } from "react-redux"

import { PersistGate } from "@plasmohq/redux-persist/integration/react"

import { persistor, store, useAppDispatch, useAppSelector } from "~store"
import {
  addUserShopItem,
  showPriceInfo
} from "~store/controller/jinritemaiProduct"

import OfferDetails, { gotointenpage } from "./OfferDetails"
import { Agreement } from "@Utils/addConfigFuncs"


// export const getStyle: PlasmoGetStyle = () => {
//   const style = document.createElement("style")
//   style.textContent = priceCommodity
//   return style
// }
// 指定挂载站点
export const config: PlasmoCSConfig = {
  matches: ["https://fxg.jinritemai.com/*"]
}

export const getInlineAnchorList: PlasmoGetInlineAnchorList = async () => {
  const urls = location.pathname === "/ffa/g/list"
  if (!urls) return
  const detailList = document.querySelectorAll(
    "tbody > tr > [class*=style_sellingPrice]"
  )
  // console.log('detailList', detailList)
  //   const elmList = []
  //   for (let i = 0; i < detailList.length; i++) {
  //     elmList.push(detailList[i])
  //   }
  return detailList
}
// export const getShadowHostId = () => "proter_top_id"
export const rendenRootDom = () => document.createElement('td')

const ShowPriceUi = (props) => {
  const dispatch = useAppDispatch()

  const getingouer = useAppSelector(
    (state) => state.jinritemaiProduct.priceinfolist
  )
  const flashWithGoodsData = useAppSelector(
    (state) => state.jinritemaiShops.shopFreightTemplateState
  )
  const isBuyStatus = useAppSelector(
    (state) => state.jinritemaiProduct.isBuyStatus
  )
  const getShowPrioStaus: any = getingouer.filter((res) => {
    return res.id === props.stid
  })[0]
  const {
    showPriter,
    turnLoading,
    // activetiItem,
    activetiGoodItem,
    getDiscountActivityFarmetData,
    getNewUserGiftFarmeData,
    supTicket,
    couponData,
    giftlist,
    getDiscountActivityOnePrdFarmetData
  } = getShowPrioStaus
  // 显示弹窗
  const [detailsStatus, setDetailsStatus] = useState(false)
  // 弹窗loding
  const [getShowDetiel, setShowDetiel] = useState(false)
  // 商品详情
  const [goodDetail, addGoodDetitsil] = useState(null)
  // 页面需要的变量数据
  const [compenterinfodata, setCompenterinfodata] = useState({
    showpritername: "",
    business_code_name: "",
    business_code_obj: {},
    selecttext: "",
    getSkuPriter: {},
    selectnum: "",
    quanhoupriter: "", // 券后价
    outinconter: "", // 限时价
    // displaySpecList: [],
    dazeconte: "", // 满减活动减去的金额
    addnumsmanjian: "", // 满减活动详情
    addnumsmanjianOne: "", // 满减活动同品多件详情
    datainfokey: false,
    giftlist: [] //优惠券列表
  })
  // 运费模板信息
  const [flashWithGoodsDataItem, setFlashWithGoodsData] = useState(null)

  // 缓存skutab
  const [displaySpecList, setdisplaySpecList] = useState(null)

  // 切换sku
  useEffect(() => {
    compenterinfodata.selectnum &&
      changeAddGoodsNum(compenterinfodata.selectnum)
  }, [displaySpecList])

  function setdata(titleid, itemid) {
    const setDataJSON = JSON.parse(JSON.stringify(goodDetail))
    const compenterinfodataJSON = JSON.parse(JSON.stringify(compenterinfodata))
    const titledatalist = JSON.parse(JSON.stringify(displaySpecList))

    compenterinfodataJSON.selecttext = ""
    compenterinfodataJSON.shopSvalue = ""
    let activettext = ""
    let outername = ""
    const selectinterid: any[] = []
    for (let i = 0; i < titledatalist.length; i++) {
      if (titledatalist[i].id === titleid) {
        const skuitemlist = titledatalist[i].values
        for (let t = 0; t < skuitemlist.length; t++) {
          if (skuitemlist[t].id === itemid) {
            skuitemlist[t].selectitem = true
          } else {
            skuitemlist[t].selectitem = false
          }
        }
      }
      titledatalist[i].values.forEach((res) => {
        if (res.selectitem) {
          compenterinfodataJSON.selecttext = `${compenterinfodataJSON.selecttext} ${res.name}`
          res.outername = res.remark ? `${res.name}(${res.remark})` : res.name
          activettext = `${activettext}/${res.name}`
          outername = `${outername}/${res.outername}`
          //   console.log('res000', res, setDataJSON, compenterinfodataJSON)

          selectinterid.push(res.id)
        }
      })
    }
    activettext = activettext.substring(1)
    outername = outername.substring(1)
    // 存在显示限时 拼团等
    compenterinfodataJSON.getSkuPriter =
      (activetiGoodItem.promotion_skus &&
        activetiGoodItem.promotion_skus.find(
          (res) =>
            res.specification === activettext || res.specification === outername
        )) ||
      (() => {
        let outrdprit = {}
        // 用 for
        setDataJSON.spec_prices.forEach((coyr) => {
          if (
            JSON.stringify(coyr.spec_detail_ids) ==
            JSON.stringify(selectinterid)
          ) {
            outrdprit = coyr
          }
        })
        return outrdprit
      })()
    if (compenterinfodataJSON.getSkuPriter?.shop_svalue) {
      compenterinfodataJSON.shopSvalue = `${(
        compenterinfodataJSON.getSkuPriter.shop_svalue / 10
      ).toFixed(1)} 折`
    }
    //   compenterinfodataJSON.stock_data = {
    //     show_stock: activetiGoodItem.promotion_skus?true:false,
    //     num: activetiGoodItem.promotion_skus && activetiGoodItem.promotion_skus.find((res) => res.specification === activettext).
    //   }
    compenterinfodataJSON.outinconter = (
      (compenterinfodataJSON.getSkuPriter.price *
        compenterinfodataJSON.selectnum) /
      100
    ).toFixed(2)
    setdisplaySpecList(titledatalist)
    // addGoodDetitsil(setDataJSON)
    setCompenterinfodata(compenterinfodataJSON)
  }
  // 获取商品详情
  function getGoodDetilData() {
    getPreviewDetail({ product_id: props.stid })
      .then((res: any) => {
        if (!res.code) {
          const setDataJSON: any = res.data
          addGoodDetitsil(setDataJSON)
          const addinfodata: any = {
            showpritername: "",
            business_code_name: "",
            business_code_obj: {},
            selecttext: "",
            getSkuPriter: {},
            selectnum: 1,
            outinconter: "",
            quanhoupriter: "",
            // displaySpecList: [],
            giftlist: giftlist
          }
          // 加入拼团判断
          if (showPriter === 1 && activetiGoodItem.business_code) {
            // 有参加限时限量购的活动
            // activetiGoodItem.activetprit = ""
            if (activetiGoodItem.business_code === "OrdinaryTimeBuy") {
              addinfodata.showpritername = "促销价"
              addinfodata.business_code_name = "普通降价促销"
              addinfodata.business_code_obj = {
                background: "transparent",
                color: "rgb(105, 113, 140)",
                border: "1px solid rgba(105, 113, 140, 0.12)"
              }
            } else if (
              activetiGoodItem.business_code === "" ||
              activetiGoodItem.business_code === "RealFlash"
            ) {
              addinfodata.showpritername = "限时价"
              addinfodata.business_code_name = "限时抢购"
              addinfodata.business_code_obj = {
                background: "transparent",
                color: " rgb(108, 38, 253)",
                border: "1px solid rgba(108, 38, 253, 0.12)"
              }
            }
          }

          addinfodata.selecttext = ""
          addinfodata.shopSvalue = ""
          let displaySpecList = setDataJSON.display_spec.displaySpecList
          let activettext = ""
          let outername = ""
          let selectinterid: any = []
          displaySpecList.forEach((res) => {
            res.values.forEach((item: any, index) => {
              if (index === 0) {
                item.selectitem = true
                item.outername = item.remark
                  ? `${item.name}(${item.remark})`
                  : item.name
                addinfodata.selecttext = `${addinfodata.selecttext} ${item.name}`
                activettext = `${activettext}/${item.name}`
                outername = `${outername}/${item.outername}`
                selectinterid.push(item.id)
              } else {
                item.selectitem = false
              }
            })
          })
          setdisplaySpecList(displaySpecList)
          activettext = activettext.substring(1)
          outername = outername.substring(1)
          addinfodata.getSkuPriter =
            (activetiGoodItem.promotion_skus &&
              activetiGoodItem.promotion_skus.find(
                (res) =>
                  res.specification === activettext ||
                  res.specification === outername
              )) ||
            (() => {
              let outrdprit = {}
              setDataJSON.spec_prices.forEach((coyr) => {
                if (
                  JSON.stringify(coyr.spec_detail_ids) ==
                  JSON.stringify(selectinterid)
                ) {
                  outrdprit = coyr
                }
              })
              return outrdprit
            })()
          addinfodata.outinconter = (
            addinfodata.getSkuPriter.price / 100
          ).toFixed(2)
          if (addinfodata.getSkuPriter?.shop_svalue) {
            addinfodata.shopSvalue = addinfodata.shopSvalue = `${(
              addinfodata.getSkuPriter.shop_svalue / 10
            ).toFixed(1)} 折`
          }
          setCompenterinfodata(addinfodata)
          setTimeout((_) => {
            setShowDetiel(true)
          }, 200)
          // 设置运费模板信息
          setFlashWithGoodsData(flashWithGoodsData[setDataJSON.freight_id])
        }
      })
      .catch((err) => {
        console.log(err)
      })
    setDetailsStatus(true)
  }
  // 设置数据返回计算返回优惠后的结果
  function changeAddGoodsNum(e) {
    // const setDataJSON = JSON.parse(JSON.stringify(goodDetail))
    const compenterinfodataJSON = JSON.parse(JSON.stringify(compenterinfodata))
    // 充重置优享受的惠券列表
    compenterinfodataJSON.giftlist = JSON.parse(JSON.stringify(giftlist))
    compenterinfodataJSON.selectnum = e
    compenterinfodataJSON.datainfokey = true
    compenterinfodataJSON.quanhoupriter = compenterinfodataJSON.outinconter =
      (() => {
        return ((compenterinfodataJSON.getSkuPriter.price * e) / 100).toFixed(2)
      })()

    // 有满减活动
    if (getDiscountActivityFarmetData.showstatus) {
      compenterinfodataJSON.addnumsmanjian = null
      // 获取满减活动数据0
      getmanjianactovt()
      // 存在满减活动的情况下
      function getmanjianactovt() {
        const getoutern = JSON.parse(
          JSON.stringify(getDiscountActivityFarmetData.discount_type_string)
        )
        // 得到总体的价格

        // 获取有满减情况下的优惠金额
        let addnums: any = null
        const sortdateont = getoutern.sort((a, b) => {
          return a.condition_value * 1 - b.condition_value * 1
        })
        let finddata = e

        sortdateont.forEach((res: any, index) => {
          if (res.condition_type === 2) {
            finddata = compenterinfodataJSON.outinconter * 1
          }
          if (
            !addnums &&
            !sortdateont[index + 1] &&
            finddata >= res.condition_value * 1
          ) {
            addnums = sortdateont[index]
            return
          }
          if (
            finddata >= res.condition_value * 1 &&
            sortdateont[index + 1].condition_value * 1 > finddata
          ) {
            addnums = res
          }
        })
        if (addnums) {
          if (addnums.condition_type === 2) {
            // compenterinfodataJSON.addnumsmanjian = addnums
            compenterinfodataJSON.dazeconte = addnums.discount
            // compenterinfodataJSON.quanhoupriter = (
            //   compenterinfodataJSON.outinconter - addnums.discount
            // ).toFixed(2)
          } else {
            const outernumber = setAddType(
              addnums,
              compenterinfodataJSON.outinconter
            )
            // compenterinfodataJSON.quanhoupriter = (
            //   compenterinfodataJSON.outinconter - outernumber
            // ).toFixed(2) // 字段还需累加
            compenterinfodataJSON.dazeconte = outernumber
            compenterinfodataJSON.addnumsmanjian = addnums
          }
          compenterinfodataJSON.giftlist.push({
            num: compenterinfodataJSON.dazeconte,
            title: '跨品多件',
            unit: addnums.title
          })
        }
      }
      function setAddType(reddata, selectactivetdata) {
        if (reddata.discount_type === 1) {
          return (selectactivetdata * ((10 - reddata.discount) / 10)).toFixed(2)
          // 打折情况
        } else if (reddata.discount_type === 3) {
          return reddata.discount
          // 满减情况
        }
      }
    }
    // 有满减多件
    if (getDiscountActivityOnePrdFarmetData.showstatus) {
      compenterinfodataJSON.addnumsmanjianOne = null
      // 获取满减活动数据0
      getmanjianactovt()
      // 存在满减活动的情况下
      function getmanjianactovt() {
        const getoutern = JSON.parse(
          JSON.stringify(getDiscountActivityOnePrdFarmetData.discount_type_string)
        )
        // 得到总体的价格

        // 获取有满减情况下的优惠金额
        let addnums: any = null
        const sortdateont = getoutern.sort((a, b) => {
          return a.condition_value * 1 - b.condition_value * 1
        })
        let finddata = e

        sortdateont.forEach((res: any, index) => {
          console.log('res12345', res, finddata, compenterinfodataJSON)
          if (res.activity_type === 1) {
            if (finddata >= res.condition_value) {
              console.log('第二件半价')
              addnums = res
            }
          }
          if (res.activity_type === 2) {
            if (finddata >= res.condition_value) {
              console.log('第二件0元')
              addnums = res
            }
          }
          if (res.activity_type === 3) {
            if (finddata >= res.condition_value) {
              addnums = res
            }
          }

        })
        if (addnums) {
          // compenterinfodataJSON.addnumsmanjianOne = addnums
          if (addnums.activity_type === 3) {
            if (addnums.discount_type === 1) {
              compenterinfodataJSON.dazeconte = ((compenterinfodataJSON.getSkuPriter.price / 100) - (compenterinfodataJSON.getSkuPriter.price / 100) * (addnums.discount_ol / 100)).toFixed(2)

            }
            if (addnums === 3) {
              compenterinfodataJSON.dazeconte = addnums.discount
            }

          } else {
            compenterinfodataJSON.dazeconte = ((compenterinfodataJSON.getSkuPriter.price / 100) - (compenterinfodataJSON.getSkuPriter.price / 100) * (addnums.discount_ol / 100)).toFixed(2)
          }
          // compenterinfodataJSON.quanhoupriter = (
          //   compenterinfodataJSON.outinconter -  compenterinfodataJSON.dazeconte
          // ).toFixed(2)

          compenterinfodataJSON.giftlist.push({
            num: compenterinfodataJSON.dazeconte,
            title: '同品多件',
            unit: addnums.title
          })
          // if (addnums.condition_type === 2) {
          //   compenterinfodataJSON.addnumsmanjian = addnums
          //   compenterinfodataJSON.dazeconte = addnums.discount
          //   compenterinfodataJSON.quanhoupriter = (
          //     compenterinfodataJSON.outinconter - addnums.discount
          //   ).toFixed(2)
          // } else {
          //   const outernumber = setAddType(addnums, compenterinfodataJSON.outinconter)
          //   compenterinfodataJSON.quanhoupriter = (
          //     compenterinfodataJSON.outinconter - outernumber
          //   ).toFixed(2)
          //   compenterinfodataJSON.dazeconte = outernumber
          //   compenterinfodataJSON.addnumsmanjian = addnums
          // }
        }
      }
      // function setAddType(reddata, selectactivetdata) {
      //   if (reddata.discount_type === 1) {
      //     return (selectactivetdata * ((10 - reddata.discount) / 10)).toFixed(2)
      //     // 打折情况
      //   } else if (reddata.discount_type === 3) {
      //     return reddata.discount
      //     // 满减情况
      //   }
      // }
    }

    const addTicketList: any = [] // 用于添加优惠券信息 判断惊喜或普通
    // 有惊喜券
    if (supTicket && supTicket.length) {
      // 存在有效的惊喜券
      // 获取所有可能的优惠券金额 比较最大值
      const getMaxList: any = []
      supTicket.forEach((res) => {
        const setOutMayData = setCouponsubType(
          res,
          res.range_type === 1 ? "全店惊喜" : "商品惊喜"
        )
        getMaxList.push(setOutMayData)
      })
      const getmaxitem = getMaxList.find(
        (maxitem) =>
          maxitem.num * 1 ===
          Math.max(...getMaxList.map((res) => res.num * 1)) * 1
      )
      if (getmaxitem && getmaxitem.num * 1) {
        addTicketList.push(getmaxitem)
      }
      function setCouponsubType(data, titleconte) {
        let outMay = compenterinfodataJSON.outinconter * 1
        const outMayConter = {
          title: titleconte,
          num: 0,
          unit: ""
        }
        if (data.coupon_sub_type === 1) {
          const threshold = data.threshold / 100
          let outerin: any = {
            num: 0,
            str: ""
          }
          if (data.credit) {
            outerin.num = (data.credit / 100).toFixed(2)
            outerin.str = parseFloat((data.credit / 100).toFixed(2))
          } else {
            outerin = (() => {
              if (
                data.dynamic_coupon_info.avg_dynamic_discount ===
                data.dynamic_coupon_info.max_dynamic_discount
              ) {
                return {
                  num: (
                    data.dynamic_coupon_info.avg_dynamic_discount / 100
                  ).toFixed(2),
                  str: parseFloat(
                    (
                      data.dynamic_coupon_info.avg_dynamic_discount / 100
                    ).toFixed(2)
                  )
                }
              }
              return {
                num: (
                  data.dynamic_coupon_info.max_dynamic_discount / 100
                ).toFixed(2),
                str: `${parseFloat(
                  (data.dynamic_coupon_info.avg_dynamic_discount / 100).toFixed(
                    2
                  )
                )}
                 - 
                 ${parseFloat(
                  (
                    data.dynamic_coupon_info.max_dynamic_discount / 100
                  ).toFixed(2)
                )}`
              }
            })()
          }

          if (outMay >= threshold) {
            outMayConter.num = outerin.num
            outMayConter.unit = `满${parseFloat(threshold.toFixed(2))}减${outerin.str
              }`
          }
        }
        if (data.coupon_sub_type === 2) {
          //   const credit = (data.credit / 100).toFixed(2)
          let outerin: any = {
            num: 0,
            str: ""
          }
          if (data.credit) {
            outerin.num = (data.credit / 100).toFixed(2)
            outerin.str = parseFloat((data.credit / 100).toFixed(2))
          } else {
            outerin = (() => {
              if (
                data.dynamic_coupon_info.avg_dynamic_discount ===
                data.dynamic_coupon_info.max_dynamic_discount
              ) {
                return {
                  num: (
                    data.dynamic_coupon_info.avg_dynamic_discount / 100
                  ).toFixed(2),
                  str: parseFloat(
                    (
                      data.dynamic_coupon_info.avg_dynamic_discount / 100
                    ).toFixed(2)
                  )
                }
              }
              return {
                num: (
                  data.dynamic_coupon_info.max_dynamic_discount / 100
                ).toFixed(2),
                str: `${parseFloat(
                  (data.dynamic_coupon_info.avg_dynamic_discount / 100).toFixed(
                    2
                  )
                )}
                 - 
                 ${parseFloat(
                  (
                    data.dynamic_coupon_info.max_dynamic_discount / 100
                  ).toFixed(2)
                )}`
              }
            })()
          }
          outMayConter.unit = `立减${outerin.str}元`
          outMayConter.num = outerin.num
        }
        if (data.coupon_sub_type === 3) {
          const discount = parseFloat((data.discount / 10).toFixed(2))
          outMayConter.unit = `${discount}折`
          outMayConter.num = parseFloat(
            (outMay * (1 - discount / 10)).toFixed(2)
          )
        }
        return outMayConter
      }
    }
    // 有优惠券
    if (couponData && couponData.length) {
      // 21：全店通用-折扣 22：全店通用-立减 23：全店通用-满减 41：指定商品-折扣 42：指定商品-立减 43：指定商品-满减
      const getMaxList: any[] = []
      const allgoods = [21, 22, 23]
      // const goodsitem = [41, 42, 43]
      couponData.forEach((res) => {
        const gettitleconter = allgoods.includes(res.couponData.favoured_type)
          ? "全店券"
          : "商品券"
        const setOutMayData = setCouponsubType(res.couponData, gettitleconter)
        // console.log(res)
        //   const setOutMayData = setCouponsubType(res, res.range_type===1?'全店惊喜':'商品惊喜')
        getMaxList.push(setOutMayData)
      })
      const getmaxitem = getMaxList.find(
        (maxitem: any) =>
          maxitem.num * 1 ===
          Math.max(...getMaxList.map((res: any) => res.num * 1)) * 1
      )
      if (getmaxitem && getmaxitem.num * 1) {
        addTicketList.push(getmaxitem)
      }
      function setCouponsubType(data, title) {
        const outmaytype = allgoods.includes(data.favoured_type)
          ? data.favoured_type - 20
          : data.favoured_type - 40
        let outMay = compenterinfodataJSON.outinconter * 1
        const outMayConter: any = {
          title: title,
          num: 0,
          unit: ""
        }
        if (outmaytype === 1) {
          const discount = parseFloat((data.discount / 10).toFixed(2))
          outMayConter.unit = `打${discount}折`
          outMayConter.num = (outMay * (1 - discount / 10)).toFixed(2)
        }
        if (outmaytype === 2) {
          outMayConter.num = (data.credit / 100).toFixed(2)
          outMayConter.unit = `立减${outMayConter.num * 1}元`
        }
        if (outmaytype === 3) {
          const threshold = data.threshold / 100
          if (outMay >= threshold) {
            const num = parseFloat((data.credit / 100).toFixed(2))
            outMayConter.num = (data.credit / 100).toFixed(2)
            outMayConter.unit = `满${parseFloat(threshold.toFixed(2))}减${num}`
          }
        }
        return outMayConter
      }
    }
    if (addTicketList && addTicketList.length) {
      const getmaxitem = addTicketList.find(
        (maxitem) =>
          maxitem.num * 1 ===
          Math.max(...addTicketList.map((res) => res.num * 1)) * 1
      )
      compenterinfodataJSON.giftlist.push(getmaxitem)
    }

    // 有优惠券的情况 需要减去 放在最后
    if (
      compenterinfodataJSON.giftlist &&
      compenterinfodataJSON.giftlist.length
    ) {
      // 有其他优惠券的情况
      // 用于处理显示金额
      // compenterinfodataJSON.quanhoupriter =
      let outmaycontent = 0
      const sortdateont = compenterinfodataJSON.giftlist.sort((a, b) => {
        return b.num * 1 - a.num * 1
      })

      // 区分优惠类型
      compenterinfodataJSON.giftlist = JSON.parse(JSON.stringify([sortdateont[0]]))
      compenterinfodataJSON.giftlist.forEach((res) => {
        outmaycontent = outmaycontent * 1 + res.num * 1
      })
      compenterinfodataJSON.quanhoupriter = (
        compenterinfodataJSON.quanhoupriter - outmaycontent
      ).toFixed(2)
      if (compenterinfodataJSON.quanhoupriter * 1 < 0.01) {
        // compenterinfodataJSON.quanhoupriter = '0.01'
        const internums = Math.abs(
          Math.abs(compenterinfodataJSON.quanhoupriter * 1) + 0.01
        )
        if (
          compenterinfodataJSON.giftlist &&
          compenterinfodataJSON.giftlist.length
        ) {
          const addfilelengt = compenterinfodataJSON.giftlist.length
          compenterinfodataJSON.giftlist[addfilelengt - 1].num =
            compenterinfodataJSON.giftlist[addfilelengt - 1].num * 1 - internums
        }
        compenterinfodataJSON.quanhoupriter = "0.01"
      }
    }
    setCompenterinfodata(compenterinfodataJSON)
    // addGoodDetitsil(setDataJSON)
  }
  const goutosetinbox = (
    <Space>
      <Button type="link" size="mini" onClick={() => gotointenpage(0)}>
        限时限量购
      </Button>
      <Button type="link" size="mini" onClick={() => gotointenpage(1)}>
        满减活动
      </Button>
      <Button type="link" size="mini" onClick={() => gotointenpage(2)}>
        新人礼金
      </Button>
      <Button type="link" size="mini" onClick={() => gotointenpage(3)}>
        惊喜券
      </Button>
      <Button type="link" size="mini" onClick={() => gotointenpage(4)}>
        优惠券
      </Button>
    </Space>
  )
  //   const [showErrCoupeters, setshowErrCoupeters] = useState(false)
  // return (
  //   <>
  //     <Popover
  //       trigger="click"
  //       content={
  //         <Space direction="vertical">
  //           <div>
  //             因近期抖店优惠券，活动等规则调整，查看策略功能暂时停止使用
  //             <br />
  //             待规则调整完毕后上线，给您造成不便敬请谅解
  //           </div>
  //           <div
  //             className="moter"
  //             style={{
  //               width: "100%",
  //               display: "flex",
  //               justifyContent: "flex-end"
  //             }}>
  //             {/* <Button
  //               size="mini"
  //               type="primary"
  //               onClick={() => {
  //                   setshowErrCoupeters(false)
  //               }}>
  //               知道了
  //             </Button> */}
  //           </div>
  //         </Space>
  //       }
  //       // visible={showErrCoupeters}
  //     >
  //       <Button
  //         //   size="mini"
  //         type="link"
  //         //   onClick={() => {
  //         //     setshowErrCoupeters(true)
  //         //   }}
  //       >
  //         查看策略
  //       </Button>
  //     </Popover>
  //   </>
  // )
  return (
    <>
      <Modal
        visible={detailsStatus}
        title="商品价格转换详情"
        okText=" 确定"
        cancelText=" 取消"
        bodyBottomMask
        keyboard
        maskClosable
        wrapClassName={"sp-main-modal"}
        footer={null}
        width={900}
        onCancel={() => setDetailsStatus(false)}
        onOk={() => setDetailsStatus(false)}>
        <OfferDetails
          detailsInfo={getShowPrioStaus}
          getShowDetiel={getShowDetiel}
          goodDetail={goodDetail}
          compenterinfodata={compenterinfodata}
          flashWithGoodsDataItem={flashWithGoodsDataItem}
          setdata={setdata}
          displaySpecList={displaySpecList}
          changeAddGoodsNum={changeAddGoodsNum}
          setDetailsStatus={setDetailsStatus}
        />
      </Modal>
      {isBuyStatus.status ? (
        <Button type="link" size="mini" onClick={() => open(isBuyStatus.url)}>
          {/* {isBuyStatus.title} */}
          商品策略
        </Button>
      ) : (
        <Space size={4} direction="vertical" style={{
          textAlign: 'right'
        }}>
          {showPriter === 0 ? (
            <Button
              type="link"
              size="mini"
              onClick={() => {
                Agreement().then(() => {
                  dispatch(showPriceInfo(props.stid))
                })

              }}
              loading={turnLoading}>
              转化价格
            </Button>
          ) : showPriter === 1 ? (
            <div className="conte">
              <p>原价 {activetiGoodItem.originalPrice}</p>
              <div className="newuserdom">
                <Tag type="default"> {activetiGoodItem.tagname}活动价</Tag>
                {activetiGoodItem.nowPrice}
              </div>
              {getDiscountActivityFarmetData.showstatus ? (
                <div className="newuserdom">
                  <Tag type="default">满减活动</Tag> x{" "}
                  {getDiscountActivityFarmetData.discount_type_string.length}{" "}
                  跨品多件优惠
                </div>
              ) : getDiscountActivityOnePrdFarmetData.showstatus ? (
                <div className="newuserdom">
                  <Tag type="default">满减活动</Tag> x{" "}
                  {getDiscountActivityOnePrdFarmetData.discount_type_string.length}{" "}
                  同品多件优惠
                </div>
              ) : (
                //   <>
                //     {...getDiscountActivityFarmetData.discount_type_string.map(
                //       (res, index) => {
                //         return (
                //           <div key={index}>
                //             <Tag type="default">满减活动</Tag>
                //             {res.title}
                //           </div>
                //         )
                //       }
                //     )}
                //   </>
                ""
              )}
              {/* 新人礼金券 */}
              {getNewUserGiftFarmeData.showstatus ? (
                <div className="newuserdom">
                  <Tag type="default">新人礼金券</Tag> x 1 张可用
                  {/* {(
                    getNewUserGiftFarmeData.allowance_info.coupon_value / 100
                  ).toFixed(2)} */}
                </div>
              ) : (
                ""
              )}
              {/* 惊喜券 */}
              {supTicket && supTicket.length ? (
                <div className="newuserdom">
                  <Tag type="default">惊喜券</Tag> x {supTicket.length} 张可用
                  {/* <>
                    {...supTicket.map((supitem, index) => {
                      return (
                        <div className="interconter" key={index}>
                          <Tag type="default">惊喜券</Tag>
                          <Tag bordered>{supitem.coutcontentinfos.goodrange}</Tag>
                          <Tag bordered>
                            {supitem.coutcontentinfos.userconter}
                          </Tag>
                          {supitem.coutcontentinfos.couponname}
                        </div>
                      )
                    })}
                  </> */}
                </div>
              ) : (
                ""
              )}
              {/* 优惠券 */}
              {couponData && couponData.length ? (
                <div className="newuserdom">
                  <Tag type="default">优惠券</Tag> x{" "}
                  {couponData.filter((e) => e.coutcontentinfos).length} 张可用
                  {/* <>
                    {...couponData.map((supitem, index) => {
                      return supitem.coutcontentinfos ? (
                        <div className="interconter" key={index}>
                          <Tag type="default">优惠券</Tag>
                          <Tag bordered>{supitem.coutcontentinfos.goodrange}</Tag>
                          <Tag bordered>
                            {supitem.coutcontentinfos.userconter}
                          </Tag>
                          {supitem.coutcontentinfos.couponname}
                        </div>
                      ) : (
                        ""
                      )
                    })}
                  </> */}
                </div>
              ) : (
                ""
              )}
              <Button
                type="link"
                size="mini"
                onClick={() => getGoodDetilData()}>
                查看详情
              </Button>
            </div>
          ) : showPriter === 3 ? (
            <>
              {/* 满减活动 */}
              {getDiscountActivityFarmetData.showstatus ? (
                <div className="newuserdom">
                  <Tag type="default">满减活动</Tag> x{" "}
                  {getDiscountActivityFarmetData.discount_type_string.length}{" "}
                  跨品多件优惠
                </div>
              ) : getDiscountActivityOnePrdFarmetData.showstatus ? (
                <div className="newuserdom">
                  <Tag type="default">满减活动</Tag> x{" "}
                  {1}{" "}
                  同品多件优惠
                </div>
              ) : (
                //   <>
                //     {...getDiscountActivityFarmetData.discount_type_string.map(
                //       (res, index) => {
                //         return (
                //           <div key={index}>
                //             <Tag type="default">满减活动</Tag>
                //             {res.title}
                //           </div>
                //         )
                //       }
                //     )}
                //   </>
                ""
              )}
              {/* 新人礼金券 */}
              {getNewUserGiftFarmeData.showstatus ? (
                <div className="newuserdom">
                  <Tag type="default">新人礼金券</Tag> x 1 张可用
                  {/* {(
                    getNewUserGiftFarmeData.allowance_info.coupon_value / 100
                  ).toFixed(2)} */}
                </div>
              ) : (
                ""
              )}
              {/* 惊喜券 */}
              {supTicket && supTicket.length ? (
                <div className="newuserdom">
                  <Tag type="default">惊喜券</Tag> x {supTicket.length} 张可用
                  {/* <>
                    {...supTicket.map((supitem, index) => {
                      return (
                        <div className="interconter" key={index}>
                          <Tag type="default">惊喜券</Tag>
                          <Tag bordered>{supitem.coutcontentinfos.goodrange}</Tag>
                          <Tag bordered>
                            {supitem.coutcontentinfos.userconter}
                          </Tag>
                          {supitem.coutcontentinfos.couponname}
                        </div>
                      )
                    })}
                  </> */}
                </div>
              ) : (
                ""
              )}
              {/* 优惠券 */}
              {couponData && couponData.length ? (
                <div className="newuserdom">
                  <Tag type="default">优惠券</Tag> x{" "}
                  {couponData.filter((e) => e.coutcontentinfos).length} 张可用
                  {/* <>
                    {...couponData.map((supitem, index) => {
                      return supitem.coutcontentinfos ? (
                        <div className="interconter" key={index}>
                          <Tag type="default">优惠券</Tag>
                          <Tag bordered>{supitem.coutcontentinfos.goodrange}</Tag>
                          <Tag bordered>
                            {supitem.coutcontentinfos.userconter}
                          </Tag>
                          {supitem.coutcontentinfos.couponname}
                        </div>
                      ) : (
                        ""
                      )
                    })}
                  </> */}
                </div>
              ) : (
                ""
              )}
              <Button
                type="link"
                size="mini"
                onClick={() => getGoodDetilData()}>
                查看详情
              </Button>
            </>
          ) : (
            <div className="conte inred">
              <p>商品未设置任何活动或优惠券</p>
              <Popover
                placement="bottom"
                title="选择设置类型"
                content={goutosetinbox}>
                <Button
                  type="link"
                  size="mini"
                //   onClick={() => setDetailsStatus(true)}
                >
                  前往设置
                </Button>
              </Popover>
            </div>
          )}
        </Space>
      )}
    </>
  )
}

// 创建dom元素
const PlasmoOverlay: FC<PlasmoCSUIProps> = (anchor) => {
  const elm = anchor.anchor?.element.parentNode?.querySelectorAll("div")
  let showdata = ""
  //   let goodTitleData = ""
  let goodTagsData: any[] = []
  if (!elm) return
  for (let i = 0; i < elm?.length; i++) {
    const title = elm[i].innerText
    // const goodTitle = elm[i].querySelector("[class*=style_productNameNew]")
    const goodTags: any = elm[i].querySelectorAll(
      '[style="color: rgb(25, 102, 255); background-color: transparent;"]'
    )
    // goodTitle && (goodTitleData = goodTitle.innerHTML)
    if (goodTags && goodTags.length) {
      goodTagsData = []
      for (let i = 0; i < goodTags.length; i++) {
        goodTagsData.push(goodTags[i].innerText)
      }
    }
    if (title.includes("ID:")) {
      showdata = title.split(":")[1]
    }
  }
  store.dispatch(
    addUserShopItem({
      id: showdata,
      showPriter: 0,
      turnLoading: false,
      //   originalPrice: "",
      //   nowPrice: "",
      //   activetiItem: null,
      //   tagname: "",
      //   goodTitleData,
      goodTagsData
    })
  )
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <div className="predlist" style={{
          textAlign: 'right',
        }}>
          <ShowPriceUi stid={showdata} />
        </div>
      </PersistGate>
    </Provider>
  )
}

export default PlasmoOverlay
